package com.errorfinding.rabbitmq.eight;

import com.errorfinding.rabbitmq.util.RabbitMqUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;

import javax.print.DocFlavor;
import java.awt.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * 消费者01
 * 交换机模式 直接模式 direct
 * 死信队列
 */
public class Consumer01 {

    //普通交换机名称
    private static final String normal_exchange="normal_exchange";
    //死信交换机名称
    private static final String dead_exchange="dead_exchange";
    //普通队列名称
    private static final String normal_queue = "normal_queue";
    //死信队列名称
    private static final String dead_queue = "dead_queue";


    //接收消息
    public static void main(String[] args) throws IOException, TimeoutException {
        //获取信道
        Channel channel = RabbitMqUtils.getChannel();
        //声明死信交换机和普通交换机 类型为 direct
        /**
         * 普通交换机
         * 参数1.交换机名称
         * 参数2.交换机类型
         */
        channel.exchangeDeclare(normal_exchange,"direct");
        //死信交换机
        channel.exchangeDeclare(dead_exchange,"direct");
        //声明死信队列和普通队列
        //普通队列转发到死信交换机参数 key是固定的
        Map<String, Object> arguments = new HashMap<>();
        //过期时间
        //arguments.put("x-message-ttl",10000);
        //正常队列设置死信交换机
        arguments.put("x-dead-letter-exchange",dead_exchange);
        //设置死信RoutingKey
        arguments.put("x-dead-letter-routing-key","lisi");
        //设置正常（普通）队列的长度限制  测试 2.普通队列达到最大长度其余消息进入死信队列
        //arguments.put("x-max-length",6);

        //普通队列
        channel.queueDeclare(normal_queue,false,false,false,arguments);
        //死信队列
        channel.queueDeclare(dead_queue,false,false,false,null);

        //绑定普通交换机与普通队列
        channel.queueBind(normal_queue,normal_exchange,"zhangsan");
        //绑定死信交换机与死信队列
        channel.queueBind(dead_queue,dead_exchange,"lisi");

        System.out.println("01等待接收消息。。。。。。。");

        //消息接收成功回调函数
        DeliverCallback deliverCallback = (tag,message)->{
            String msg =  new String(message.getBody(),"UTF-8");

            if (msg.equals("info5")){
                System.out.println("01拒绝的消息是："+msg);
                //拒绝消息 测试 3.消息被拒绝进入死信队列
                channel.basicReject(message.getEnvelope().getDeliveryTag(),false);
            }else{
                System.out.println("01接收的消息是："+msg);
                channel.basicAck(message.getEnvelope().getDeliveryTag(),false);
            }

        };
        //接收消息
        //channel.basicConsume(normal_queue,true,deliverCallback,tag->{});
        channel.basicConsume(normal_queue,false,deliverCallback,tag->{});//开启手动应答 测试 3.消息被拒绝进入死信队列

    }

}
